package com.zxd.interview.mycache.version2;

import com.zxd.interview.mycache.compute.ComputeAble;
import com.zxd.interview.mycache.compute.ExpensiveCompute;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 第二版，使用装饰模式进行改造
 * synchronized 同步加锁
 * @author
 * @version v1.0.0
 * @Package : com.zxd.interview.mycache.version2
 * @Description : 使用装饰模式进行改造
 * @Create on : 2023/6/15 16:29
 **/
@Slf4j
public class MyCacheVersion2 {

    /**
     * 缓存
     */
    private final Map<String, Integer> cache = new HashMap<>();
    /**
     * 计算方法实现对象
     */
    private final static ComputeAble<String, Integer> COMPUTE = new ExpensiveCompute();

    public synchronized Integer compute(String userId) throws Exception {
        if(cache.containsKey(userId)){
            log.info("cached => {}", userId);
            return cache.get(userId);
        }
        log.info("doCompute => {}", userId);
        Integer result = doCompute(userId);
        //不存在缓存就加入
        cache.put(userId, result);
        return result;
    }

    /**
     * 计算方法由具体的类实现封装
     * @param userId
     * @return
     * @throws InterruptedException
     */
    private Integer doCompute(String userId) throws Exception {
        return COMPUTE.doCompute(userId);
    }
}
